package com.example.jimingxuan

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.jimingxuan.R
import java.io.File
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity() {
    private lateinit var minNumber: EditText
    private lateinit var maxNumber: EditText
    private lateinit var startButton: Button
    private lateinit var stopButton: Button
    private lateinit var resultTextView: TextView
    private lateinit var toolbar: Toolbar
    private val handler = Handler(Looper.getMainLooper())
    private val executor = Executors.newSingleThreadExecutor()
    private var isCalculating = false
    private val primes = mutableListOf<Int>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        minNumber = findViewById(R.id.minNumber)
        maxNumber = findViewById(R.id.maxNumber)
        startButton = findViewById(R.id.startButton)
        stopButton = findViewById(R.id.stopButton)
        resultTextView = findViewById(R.id.resultTextView)

        startButton.setOnClickListener { startCalculation() }
        stopButton.setOnClickListener { stopCalculation() }

        loadPrimes()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.history -> {
                startActivity(Intent(this, HistoryActivity::class.java))
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun startCalculation() {
        val min = minNumber.text.toString().toIntOrNull() ?: return
        val max = maxNumber.text.toString().toIntOrNull() ?: return
        isCalculating = true
        primes.clear()
        resultTextView.text = ""
        executor.execute {
            for (i in min..max) {
                if (!isCalculating) break
                if (isPrime(i)) {
                    primes.add(i)
                    handler.post {
                        resultTextView.append("$i\n")
                    }
                }
            }
            savePrimes()
        }
    }

    private fun stopCalculation() {
        isCalculating = false
    }

    private fun isPrime(num: Int): Boolean {
        if (num < 2) return false
        for (i in 2..Math.sqrt(num.toDouble()).toInt()) {
            if (num % i == 0) return false
        }
        return true
    }

    private fun savePrimes() {
        val file = File(filesDir, "primes.txt")
        file.writeText(primes.joinToString("\n"))
    }

    private fun loadPrimes() {
        val file = File(filesDir, "primes.txt")
        if (file.exists()) {
            val savedPrimes = file.readLines().map { it.toInt() }
            primes.addAll(savedPrimes)
            resultTextView.text = savedPrimes.joinToString("\n")
        }
    }
}